// pages/Goods/Evaluation/Evaluation.js
//获取应用实例
const app = getApp();
const assetsAddress = app.globalData.global.assetsIp + '/' + app.globalData.global.assetsName;
import { getGoodsOrder } from '../../../api/order';
import { queryGoodsEvaluationInfo , updateGoodsEvaluationSupport , updateGoodsEvaluationCommentReply } from '../../../api/goods';
import { throttle , checkFile } from '../../../utils/util';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    shareTitle: app.globalData.global.shareTitle,
    assetsAddress: assetsAddress,
    tabList: [
      { id: '3', name: '待评价'},{ id: '4', name: '已评价'}
    ],
    active: '3',
    page: 0,
    total: 0,
    loading: true,
    noMore: false,
    loadingFailed: false,
    isReachBottom: false,
    dataList: [],
    showFieldModal: false,
    commentCont: '', // 评论内容
    item: {},
    commentId: '', // 某条回复ID
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if(this.data.active == '3'){
      this._getGoodsOrder()
    }else{
      this._queryGoodsEvaluationInfo();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      page: 0,
      isReachBottom: false,
      noMore: false,
      loading: false,
      loadingFailed: false,
      dataList: [],
    })
    if(this.data.active == '3'){
      this._getGoodsOrder()
    }else{
      this._queryGoodsEvaluationInfo();
    }
    setTimeout(()=>{
      wx.stopPullDownRefresh({
        success: (res) => {
          console.log(res,'刷新成功')
          wx.showToast({
            title: '刷新成功',
            icon: 'none',
          })
        },
      })
    },1000)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: throttle(function(){
    console.log('上拉加载')
    if(this.data.isReachBottom){
      if(this.data.active == '3'){
        this._getGoodsOrder()
      }else{
        this._queryGoodsEvaluationInfo();
      }
    }
  },500),

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let userId = wx.getStorageSync('userId')
    return {
      title: this.data.shareTitle,
      path: '/pages/Welcome/Welcome?scene='+userId,
    }
  },
  // 获取所有评价数据
  _getGoodsOrder(){
    let _this = this;
    getGoodsOrder({page: _this.data.page,orderStatus: _this.data.active})
    .then(res => {
      if(res.success){
        var list = _this.data.dataList;
        for (let index = 0; index < res.data.content.length; index++) {
          const item = res.data.content[index];
          item.goodsInfo = JSON.parse(item.goodsInfo)
          if(item.imageUrl && item.imageUrl != 'null' && item.imageUrl != ''){
            item.imageUrl = item.imageUrl.split(',')
          }else{
            item.imageUrl = []
          }
        }
        if(_this.data.page == 0){
          list = res.data.content;
        }else{
          list = list.concat(res.data.content);
        }
        _this.setData({
          dataList: list,
          total: res.data.totalElements,
          page: _this.data.page+1,
        })
        if(_this.data.page * 10 >= res.data.totalElements){
          _this.setData({
            isReachBottom: false,
            noMore: true,
            loading: false,
            loadingFailed: false,
          })
        }else{
          _this.setData({
            isReachBottom: true,
            noMore: false,
            loading: false,
            loadingFailed: false,
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取所有评价数据
  _queryGoodsEvaluationInfo(){
    let _this = this;
    queryGoodsEvaluationInfo({page: _this.data.page,isOnlyQuerySelf: '1'})
    .then(res => {
      if(res.success){
        var list = _this.data.dataList;
        for (let index = 0; index < res.data.content.length; index++) {
          const item = res.data.content[index];
          item.goodsInfo = JSON.parse(item.goodsInfo)
          if(item.imageUrl && item.imageUrl != 'null' && item.imageUrl != ''){
            item.imageUrl = item.imageUrl.split(',')
            var fileList = []
            for (let j = 0; j < item.imageUrl.length; j++) {
              const img = item.imageUrl[j];
              var types = checkFile(img);
              if(types == 'video'){
                fileList.push({url: img,isVideo: true,deletable: true})
              }else if(types == 'image'){
                fileList.push({url: img,isImage: true,deletable: true})
              }
            }
            item.imageUrl = fileList;
          }else{
            item.imageUrl = []
          }
          if(item.goodsEvaluationExtraDTO && item.goodsEvaluationExtraDTO.imageUrl && item.goodsEvaluationExtraDTO.imageUrl != 'null' && item.goodsEvaluationExtraDTO.imageUrl != ''){
            var imageUrls = item.goodsEvaluationExtraDTO.imageUrl.split(',');
            var fileList = []
            for (let j = 0; j < imageUrls.length; j++) {
              const img = imageUrls[j];
              var types = checkFile(img);
              if(types == 'video'){
                fileList.push({url: img,isVideo: true,deletable: true})
              }else if(types == 'image'){
                fileList.push({url: img,isImage: true,deletable: true})
              }
            }
            item.goodsEvaluationExtraDTO.imageUrls = fileList;
          }else if(item.goodsEvaluationExtraDTO){
            item.goodsEvaluationExtraDTO.imageUrls = []
          }
        }
        if(_this.data.page == 0){
          list = res.data.content;
        }else{
          list = list.concat(res.data.content);
        }
        _this.setData({
          dataList: list,
          page: _this.data.page+1,
        })
        if(_this.data.page * 10 >= res.data.totalElements){
          _this.setData({
            isReachBottom: false,
            noMore: true,
            loading: false,
            loadingFailed: false,
          })
        }else{
          _this.setData({
            isReachBottom: true,
            noMore: false,
            loading: false,
            loadingFailed: false,
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // tab切换
  onChange(e){
    console.log(e)
    this.setData({
      page: 0,
      isReachBottom: false,
      noMore: false,
      loading: false,
      loadingFailed: false,
      active: e.detail.name,
      dataList: [],
    })
    if(this.data.active == '3'){
      this._getGoodsOrder()
    }else{
      this._queryGoodsEvaluationInfo();
    }
  },
  // 去评价
  goNextEvent(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    let goods = e.target.dataset.goods||e.currentTarget.dataset.goods;
    let url = e.target.dataset.name||e.currentTarget.dataset.name;
    item.goodsInfo = [goods];
    wx.navigateTo({
      url: `${url}?item=${JSON.stringify(item)}`,
    })
  },
  // 页面跳转
  goNext(e){
    let type = e.target.dataset.type||e.currentTarget.dataset.type;
    let url = e.target.dataset.name||e.currentTarget.dataset.name;
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    // console.log(JSON.stringify(item))
    // return
    if(item){
      if(type == 1){
        wx.switchTab({
          url: `${url}`,
        })
      }else{
        wx.navigateTo({
          url: `${url}?item=${JSON.stringify(item)}`,
        })
      }
    }else{
      if(type == 1){
        wx.switchTab({
          url: `${url}`,
        })
      }else{
        wx.navigateTo({
          url: `${url}`,
        })
      }
    }
  },
  // 点赞评论
  support(e){
    let _this = this;
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    updateGoodsEvaluationSupport({evaluationId: item.id,isSupport: item.isSupport == '1' ? '0' : '1'})
    .then(async res => {
      if(res.success){
        wx.showToast({
          title: item.isSupport == '1' ? '取消点赞' : '点赞成功',
          icon: 'success',
        })
        try {
          var itemn = await _this.getOneData(item.id);
          var index = _this.data.dataList.findIndex(items => items.id == item.id);
          var list = _this.data.dataList;
          list[index] = itemn;
          _this.setData({
            dataList: list,
          })
        } catch (error) {
          wx.showToast({
            title: error,
            icon: 'none'
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 查询单条评论数据
  getOneData(id){
    return new Promise((resolve,reject) => {
      queryGoodsEvaluationInfo({id: id,isOnlyQuerySelf: '1'})
      .then(res => {
        if(res.success){
          var item = res.data.content[0];
          item.goodsInfo = JSON.parse(item.goodsInfo)
          if(item.imageUrl && item.imageUrl != 'null' && item.imageUrl != ''){
            item.imageUrl = item.imageUrl.split(',')
            var fileList = []
            for (let j = 0; j < item.imageUrl.length; j++) {
              const img = item.imageUrl[j];
              var types = checkFile(img);
              if(types == 'video'){
                fileList.push({url: img,isVideo: true,deletable: true})
              }else if(types == 'image'){
                fileList.push({url: img,isImage: true,deletable: true})
              }
            }
            item.imageUrl = fileList;
          }else{
            item.imageUrl = []
          }
          resolve(item)
        }else{
          reject(res.errMessage)
        }
      })
    })
  },
  // 展示评论输入框
  showCommentIpt(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    this.setData({
      item: item,
      showFieldModal: true,
      commentCont: '',
      commentId: '',
    })
  },
  // 单独回复某条评论
  showCommentId(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    let commentId = e.target.dataset.commentid||e.currentTarget.dataset.commentid;
    this.setData({
      item: item,
      showFieldModal: true,
      commentCont: '',
      commentId: commentId,
    })
  },
  // 输入框失去焦点隐藏输入框
  commentNBlur(){
    this.setData({
      showFieldModal: false,
    })
  },
  commentContChange(e){
    this.setData({
      commentCont: e.detail,
    })
  },
  // 回复评论内容
  commentSubmit(){
    let _this = this;
    if(_this.data.commentCont == ''){
      return
    }else{
      updateGoodsEvaluationCommentReply({evaluationId: _this.data.item.id,content: _this.data.commentCont,commentId: _this.data.commentId})
      .then(async res => {
        if(res.success){
          wx.showToast({
            title: _this.data.commentId != '' ? '回复成功' : '评论成功',
            icon: 'success',
          })
          try {
            var itemn = await _this.getOneData(_this.data.item.id);
            var index = _this.data.dataList.findIndex(items => items.id == _this.data.item.id);
            var list = _this.data.dataList;
            list[index] = itemn;
            console.log(itemn,'itemn')
            console.log(index,'index');
            console.log(list,'list');
            // return;
            _this.setData({
              dataList: list,
            })
          } catch (error) {
            wx.showToast({
              title: error,
              icon: 'none'
            })
          }
        }else{
          wx.showToast({
            title: res.errMessage,
            icon: 'none',
          })
        }
      })
    }
  }
})